<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @abstract 客户自定义费用
 * @author zxj
 *
 */
class CustomerPrice extends MY_Controller {
	private $t_Cprice = 'mt_customer_price';  //自定义价格表
	function __construct() {
		parent::__construct();
        $this->output->enable_profiler(TRUE);
	}


    /**
     * 列表
     */
    function index()
    {
        //获取表单数据
        $data = $formField = gp();
        //#查询条件
        $searchStr = 'users/CustomerPrice/index/?';
        $keyword = addslashes(trim($data['keyword']));
        if ($keyword) {
            if (filter_var($keyword, FILTER_VALIDATE_EMAIL)) {
                $where = 'where b.email = \'' . $keyword . '\' ';
            } else {
                $where = 'where (d.name_en like \'%' . $keyword . '%\' or d.name_ch like \'%' . $keyword . '%\' or b.name like \'%' . $keyword . '%\') ';
            }
            $searchStr .= 'keyword=' . $keyword;
        }
        //服务中心
        $site_id = intval($data['site_id']);
        if ($site_id) {
            $where = $where ? $where . ' and ' : ' where ';
            $where .= 'a.site_id=' . $site_id;
            $searchStr .= '&site_id=' . $site_id;
        }
        //产品类型
        $category_id = intval($data['category_id']);
        if ($category_id) {
            $where = $where ? $where . ' and ' : ' where ';
            $where .= 'a.category_id=' . $category_id;
            $searchStr .= '&category_id=' . $category_id;
        }
        //维修等级
        $grade = intval($data['grade']);
        if ($grade) {
            $where = $where ? $where . ' and ' : ' where ';
            $where .= 'a.grade=' . $grade;
            $searchStr .= '&grade=' . $grade;
        }
        //客户编号
        $customer_id = intval($data['customer_id']);
        if ($customer_id) {
            $where = $where ? $where . ' and ' : ' where ';
            $where .= 'a.customer_id=' . $customer_id;
            $searchStr .= '&customer_id=' . $customer_id;
        }
        //品牌编号
        $brand_id = intval($data['brand_id']);
        if ($brand_id) {
            $where = $where ? $where . ' and ' : ' where ';
            $where .= 'a.brand_id=' . $brand_id;
            $searchStr .= '&brand_id=' . $brand_id;
        }
        $optCategory[$category_id] = 'selected';
        $data['optCategory'] = $optCategory;
        $optGrade[$grade] = 'selected';
        $data['optGrade'] = $optGrade;
        $optCustomer[$customer_id] = 'selected';
        $data['optCustomer'] = $optCustomer;
        $optBrand[$brand_id] = 'selected';
        $data['optBrand'] = $optBrand;
        $optServiceCenter[$site_id] = 'selected';
        $data['optServiceCenter'] = $optServiceCenter;
        //分页
        $this->load->library('pagination');
        $config['page_query_string'] = TRUE;
        $config['base_url'] = blang_url($searchStr);
        $sql = 'select a.*,b.name as customerName,b.email,b.type,c.name_ch as siteName,c.point,c.currency,d.category,d.name_ch as itemName,d.name_en,d.isDefault from mt_customer_price as a
                left join mt_customers as b on a.customer_id = b.id
                left join mt_service_center as c on a.site_id = c.id
                left join mt_product_repair_item as d on a.labor_id = d.id ' . $where;
        $config['total_rows'] = $this->common_model->getQuery($sql, 'num_rows');
        $config['per_page'] = 20;
        $page = max(1, intval($data['page']));
        $config['uri_segment'] = config_item('enable_lang') ? 5 : 4;
        $offset = ($page - 1) * $config['per_page'];
        $this->pagination->initialize($config);
        $sql .= ' order by a.add_time desc limit ' . $offset . ',' . $config['per_page'] . ' ';
        $dataList = $this->common_model->getQuery($sql, 'result_array');
        $data['show_pages'] = $this->pagination->create_links();
        //重构数据
        foreach ($dataList as $key => &$rs) {
            $brandOne = $this->common_model->selectFirst('mt_customers',array('id'=>$rs['brand_id']));
            $rs['brandName'] = $brandOne['name'];
            $rs['add_time'] = date('Y-m-d H:i:s', $rs['add_time']);
        }
        unset($rs);
        $data['dataList'] = $dataList;
        //查询服务站点
        $serviceCenterList = $this->common_model->selectall('mt_service_center');
        $data['serviceCenterList'] = $serviceCenterList;
        //查询客户列表
        $customerList = $this->common_model->selectCustom('mt_customers', array('type'=>1));
        $data['customerList'] = $customerList;
        //查询品牌列表
        $brandList = $this->common_model->selectCustom('mt_customers', array('type'=>2));
        $data['brandList'] = $brandList;
        //查询产品类型
        $categoryList = $this->common_model->selectCustom('mt_product_category');
        $data['categoryList'] = $categoryList;
        //查询维修等级
        $gradeList = $this->common_model->selectall('mt_repair_grade');
        $data['gradeList'] = $gradeList;

        if ($this->debug) {
            gsh_output($data);
        }
        //views
        $this->breadcrumb->append_crumb(
            array('url' => 'users/CustomerPrice/edit', 'name' => '批量修改')
        );
        //视图以及样式
        $data['curLang'] = $this->curLang;
        $this->load->view('defaults/customerPrice_list', $data);
        $this->load->view('defaults/common/footer');
    }



    /**
     * 新增OR更新
     */
    function add()
    {
        //表单处理
        $data['post_type'] = __FUNCTION__;
        //接收数据
        $formData = gp();
        if ($formData['submits']) {
            $fieldsList = $this->db->list_fields('mt_customer_price');
            $where = $inData = array();
            foreach ($formData as $key=>$val) {
                if($val && in_array($key,$fieldsList)){
                    $where[$key]=$val;
                    $inData[$key] = $val;
                }
            }
            $laborList = $this->common_model->selectCustom('mt_customer_price', $where);
            //更新数据
            if($laborList){
                foreach ($laborList as $rs) {
                    $id = $rs['id'];
                    $price = (float)$formData['laborPrice'.$id];
                    gsh_output($where);
                    $this->common_model->update('mt_customer_price',array('price'=>$price),array('id'=>$id));
                }
            }else{
                //插入数据
                unset($where['customer_id']);
                unset($where['brand_id']);
                $inData['add_time'] = time();
                $inData['add_user'] = $this->users['account'];
                $laborList = $this->common_model->selectCustom('mt_base_price',$where);
                foreach ($laborList as $rs) {
                    $id = $rs['id'];
                    $price = (float)$formData['laborPrice'.$id];
                    $inData['price'] = $price;
                    $inData['labor_id'] = $rs['labor_id'];
                    $inData['base_price'] = $rs['merchant_price'];
                    gsh_output($inData);
                    $this->common_model->insert('mt_customer_price',$inData);
                }
            }
            //跳转
           // redirect('users/CustomerPrice/');
        }
        //查询服务站点
        $serviceCenterList = $this->common_model->selectall('mt_service_center');
        $data['serviceCenterList'] = $serviceCenterList;
        //查询客户列表
        $customerList = $this->common_model->selectCustom('mt_customers', array('type'=>1));
        $data['customerList'] = $customerList;
        //查询品牌列表
        $brandList = $this->common_model->selectCustom('mt_customers', array('type'=>2));
        $data['brandList'] = $brandList;
        //查询产品类型
        $categoryList = $this->common_model->selectCustom('mt_product_category');
        $data['categoryList'] = $categoryList;
        //维修项等级
        $gradeList = $this->common_model->selectCustom('mt_repair_grade');
        $data['gradeList'] = $gradeList;
        //views
        $this->breadcrumb->append_crumb(
            array('url' => 'users/CustomerPrice/', 'name' => '列表')
        );
        //views
        $this->breadcrumb->append_crumb(
            array('url' => 'users/CustomerPrice/edit', 'name' => '批量修改')
        );
        $this->load->view('defaults/customerPrice_post', $data);
        $this->load->view('defaults/common/footer');

    }


    /**
     * 维修项手工费
     * @param string $category_id 类型ID  判断产品类型
     * @param string $customer_id 客户ID  判断客户类型
     * @return false;
     */
    function laborPrice($category_id = '',$customer_id=''){
        $category_id = $category_id?$category_id:gp('category_id');
        $customer_id = $customer_id?$customer_id:gp('customer_id');
        if(!$category_id || !$customer_id)return false;
        $customerTypeAry = array(1=>'merchant_price',2=>'brand_price',3=>'individual_price');
        $customers =  $this->common_model->selectFirst('mt_customers', array('id' => $customer_id));
        $sql = 'select b.id,b.site_id,b.labor_id,b.brand_price,b.individual_price,b.merchant_price,b.ru_individual_price,
                a.category,a.name_ch,a.grade,a.isDefault,c.name_ch as siteName,c.point,c.currency from mt_base_price as b
                left join mt_product_repair_item as a on a.id = b.labor_id
                left join mt_service_center as c on b.site_id = c.id
                where category = '.$category_id.' order by c.id asc ,a.grade asc';
        $laborList = $this->common_model->getQuery($sql, 'result_array');
        foreach ($laborList as &$rs) {
            $priceType = $customerTypeAry[$customers['type']];
            $rs['laborPrice'] = $rs[$priceType];
        }
        unset($rs);
        return $laborList;
    }


    /**
     * 修改金额
     */
    function edit()
    {
        //表单处理
        $data['post_type'] = __FUNCTION__;
        //接收数据
        $formData = gp();
        if ($formData['submits']) {
            //判断是否修改基础费用
            if ($formData['customer_id']) {
                $where = array(
                    'customer_id' => $formData['customer_id'],
                    'site_id' => $formData['site_id'],
                    'category_id' => $formData['category_id'],
                    'grade' => $formData['grade'],
                );
                if($formData['brand_id']){
                    $where['brand_id'] = $formData['brand_id'];
                }
                $inData = array(
                    'price' => $formData['price'],
                );
                $this->common_model->update('mt_customer_price', $inData, $where);
            } else {
                $where = array(
                    'site_id' => $formData['site_id'],
                    'category_id' => $formData['category_id'],
                    'grade' => $formData['grade'],
                );
                $inData = array(
                    'merchant_price' => $formData['merchant_price'],
                    'individual_price' => $formData['individual_price'],
                    'brand_price' => $formData['brand_price'],
                );
                //判断基础费用是否存在，不存在则添加
                $basePriceList = $this->common_model->selectCustom('mt_base_price', $where);
                if (!$basePriceList) {
                    $repairItemList = $this->common_model->selectCustom('mt_product_repair_item', array('category'=>$formData['category_id'],'grade'=>$formData['grade']));
                    foreach ($repairItemList as $item) {
                        $inData['site_id'] = $formData['site_id'];
                        $inData['category_id'] = $item['category'];
                        $inData['grade'] = $item['grade'];
                        $inData['labor_id'] = $item['id'];
                        $this->common_model->insert('mt_base_price',$inData);
                    }
                } else {
                    $this->common_model->update('mt_base_price', $inData, $where);
                }
            }
            //跳转
            redirect('users/CustomerPrice/');
        }
        //查询服务站点
        $serviceCenterList = $this->common_model->selectall('mt_service_center');
        $data['serviceCenterList'] = $serviceCenterList;
        //查询产品类型
        $categoryList = $this->common_model->selectCustom('mt_product_category');
        $data['categoryList'] = $categoryList;
        //查询客户列表
        $customerList = $this->common_model->selectCustom('mt_customers', array('type'=>1));
        $data['customerList'] = $customerList;
        //查询品牌列表
        $brandList = $this->common_model->selectCustom('mt_customers', array('type'=>2));
        $data['brandList'] = $brandList;
        //查询维修等级
        $gradeList = $this->common_model->selectall('mt_repair_grade');
        $data['gradeList'] = $gradeList;
        //views
        $this->breadcrumb->append_crumb(
            array('url' => 'users/CustomerPrice/', 'name' => '列表')
        );
        $this->load->view('defaults/customerPrice_edit', $data);
        $this->load->view('defaults/common/footer');

    }



}
